/**
 * There are code generation
 */
package com.neusoft.lohas.modules.ivm.service.product;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.service.BaseService;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.modules.ivm.entity.product.Supplier;
import com.neusoft.lohas.modules.ivm.utils.MerchantUtils;
import com.neusoft.lohas.modules.ivm.utils.ProductUtils;
import com.neusoft.lohas.modules.ivm.dao.product.SupplierDao;

/**
 * 供应商Service
 * @author Jackie.Liu
 * @version 2014-12-30
 */
@Component
@Transactional(readOnly = true)
public class SupplierService extends BaseService {

	@Autowired
	private SupplierDao supplierDao;
	
	public Supplier get(String id) {
		return supplierDao.get(id);
	}
	
	public Page<Supplier> find(Page<Supplier> page, Supplier supplier) {
		DetachedCriteria dc = supplierDao.createDetachedCriteria();
		if (StringUtils.isNotEmpty(supplier.getName())){
			dc.add(Restrictions.like("name", "%"+supplier.getName()+"%"));
		}
		dc.add(Restrictions.eq("merchant.id", MerchantUtils.getMerchant().getId()));
		dc.add(Restrictions.eq(Supplier.FIELD_DEL_FLAG, Supplier.DEL_FLAG_NORMAL));
		dc.addOrder(Order.asc("createDate"));
		return supplierDao.find(page, dc);
	}
	
	@Transactional(readOnly = false)
	public void save(Supplier supplier) {
		supplierDao.save(supplier);
		ProductUtils.removeCache(ProductUtils.CACHE_SUPPLIER_LIST);
	}
	
	@Transactional(readOnly = false)
	public void delete(String id) {
		supplierDao.deleteById(id);
		ProductUtils.removeCache(ProductUtils.CACHE_SUPPLIER_LIST);
	}

	public Supplier getSupplierByName(String merchantId, String name) {
		return supplierDao.findBySql(merchantId, name);
	}
	
}
